package client;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.EventLoop;
import io.netty.util.concurrent.EventExecutorGroup;

import java.util.concurrent.TimeUnit;

public class MyClientPipeline extends ChannelInboundHandlerAdapter {

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx){
        System.out.println("没连上--");
        ctx.close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        System.out.println("异常了---" + cause.getMessage());
        ctx.close();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("掉线了--");
        ctx.close();
        new Thread(() -> {
            try {
                MyClientBoot myClientBoot = new MyClientBoot();
                myClientBoot.connect();
                Thread.sleep(500);
            } catch (Exception e){
            }
        }).start();

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("连接成功");
        ByteBuf buffer = ctx.alloc().buffer();
        ctx.writeAndFlush(buffer.writeLong(System.currentTimeMillis()));
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf b= (ByteBuf)msg;
        long l = b.readLong();
        long now = System.currentTimeMillis();
        System.out.println("ping:"+(now-l));
        Thread.sleep(100);
        ctx.writeAndFlush(ctx.alloc().buffer().writeLong(System.currentTimeMillis()));
    }

}
